<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Log;
use think\captcha\Captcha;
use think\Request;
use app\admin\model\Base;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use app\admin\controller\system\SmsTemplate;
use app\common\controller\system\Docking;


class Login extends Controller
{
    public function __construct()
    {
        parent::__construct();

        //输出系统信息
        $systemInfo = (new System())->getSystemInfo();
        $this->assign('systemInfo',$systemInfo);

        //初始化日志保存目录
        $requestName = Request::instance()->module();
        $controllerName = Request::instance()->controller();
        $setPath = strtolower("{$requestName}/{$controllerName}/");
        Log::init(['path'=>LOG_PATH.$setPath,'type'  => 'file',]);
    }

    //    用户登录  推广页面
    public function register()
    {
//  	echo 44;die;
        //记录到访用户信息 做推广ua统计
        $this->addUserVisitRecord(1,input('puser'));

//  	获取系统名称
        $data=Db::table('xb_sys_basicinfo')->find();
        $webTile = (new System())->getSystemInfo();
        $this->assign('title',$webTile['SystemName']);
        $this->assign('data',$data);
        $puser=input('puser');
        $this->assign('puser',$puser);
        return $this->fetch();
    }


    /**
     * 后台登陆
     */
    public function login()
    {
        if(request()->isAjax())
        {
            //验证post数据
            $postData = Request()->only('Mobile,Password,MsgCode,mac');
            $result = $this->validate($postData,'Login.login');
            if($result !== true){
                return ajaxErrorResult($result);
            }

            //获取用户信息与
            $userInfo = db('sys_administrator')->where(['UserName|Mobile' => $postData['Mobile']])->find();
            if(!$userInfo){
                return ajaxErrorResult('用户信息不存在');
            }
            if($userInfo['Status'] == 0){
                return ajaxErrorResult('账户已禁用，请联系管理员');
            }
            if($userInfo['IsDel'] == 1){
                return ajaxErrorResult('账户已删除，请联系管理员');
            }

            if($userInfo['LoginType'] == 1){//手机登陆

                //验证请求字段
                if(!isset($postData['MsgCode']) || empty($postData['MsgCode'])){
                    return ajaxErrorResult('请输入短信验证码');
                }

                //校验短信验证码
                $msgCode = db('sms_code')->where(['Name' => $userInfo['Mobile']])->order('id','desc')->field(['Code','UpdateTime'])->find();
                if(!$msgCode){
                    return ajaxErrorResult('请发短信送验证码');
                }
                if((strtotime($msgCode['UpdateTime'])+300) < time()){
                    return ajaxErrorResult('短信验证码已过期，请重新发送');
                }
                if($msgCode['Code'] != $postData['MsgCode']){
                    return ajaxErrorResult('短信验证码不正确，请重新输入');
                }
            }else if($userInfo['LoginType'] == 2){//密码登陆

                //验证请求字段
                if(!isset($postData['Password']) || empty($postData['Password'])){
                    return ajaxErrorResult('请输入密码');
                }
                if(md5($postData['Password']) != $userInfo['Password']){
                    return ajaxErrorResult('密码错误');
                }
            }else{
                return ajaxErrorResult('登陆方式不存在，禁止登陆');
            }

            $ip = request()->ip();
            if($ip == '127.0.0.1'){
                $loginIp = '本地登录';
            }else{
                $loginIp = getCity($ip);
            }

            $temp = [
                'ID'        => $userInfo['ID'],
                'LoginTime' => date('Y-m-d H:i:s',time()),
                'LoginIP'   => $ip,
                'IpCity'    => $loginIp,
            ];

            $upUserInfo = db('sys_administrator')->update($temp);
            if($upUserInfo){

                session('id',$userInfo['ID']);
                session('info',$userInfo);
                (new Common())->logs('登录');

                return ajaxSuccessResult('','登陆成功，即将跳转个人中心');
            }else{
                return ajaxErrorResult('登陆失败');
            }
        }

        //获取系统名称
        $data=Db::table('xb_sys_basicinfo')->find();
        $webTile = (new System())->getSystemInfo();
        $this->assign('title',$webTile['SystemName']);
        $this->assign('data',$data);

        return $this->fetch();
    }

    //    用户登录
    public function loginss(){

        $data=Request()->param();
        $mac =$data['mac']?$data['mac']:null;
        $verify =$data['verify'];
        $username=$data['username'];
        if(preg_match("/^1[345678]{1}\d{9}$/",$username)){
            $ret = Db::table('xb_sys_administrator')->where('Mobile',$username)->find();
        }else{//不是手机号
            $ret = Db::table('xb_sys_administrator')->where('UserName',$username)->find();
            if(!$ret){
                $code='204';
                $message='用户不存在!';
            }else{
                $username=$ret['Mobile'];
            }
        }
        if($ret['isMAC']==1){//此人开启MAC验证
            if($mac==null){
                return json(['code'=>'204','msg'=>'无法匹配,请更换浏览器或联系管理员']);
            }
            if($mac !=$ret['MAC']){
                return json(['code'=> '204','msg'=> '请用已配置的MAC电脑登录']);
            }
        }
        $sms =Db::table('xb_sms_code')->where('Name',$username)->order('UpdateTime desc')->find();
        $time =time();
        $codeTime = strtotime($sms['UpdateTime']);
        if($time-$codeTime>60){
            return json(['code'=> '204','msg'=>'验证码已过期']);
        }
        if(is_null($ret)){
            $code='204';
            $message='用户不存在';
        }elseif($verify!=$sms['Code']){
            $message='验证码不正确';
            $code='204';
        }else{
            $status='1';
            $code='0';
            $message='验证通过,芝麻开门';
            session('id',$ret['ID']);
            session('info',$ret);
            $update['LoginTime'] = date('Y-m-d H:i:s');
            $update['LoginIP']= $_SERVER["REMOTE_ADDR"];
            if($update['LoginIP']="127.0.0.1"){
                $update['IpCity'] = '本地登录';
            }else{
                $update['IpCity'] = getCity($update['LoginIP']);
            }
            Db::table('xb_sys_administrator')->where('Mobile',$username)->update($update);
            (new Common())->logs('登录');
        }
        return json(['code'=>$code,'msg'=>$message]);
    }

    //   用户退出
    public function loginout()
    {
        (new Common())->logs('退出');
        session('id',null);
        session('info',null);
        return $this->redirect('admin/login/login');
    }

    /**
     * 验证码
     */
    public function verify()
    {
        $captcha = new Captcha();
        $captcha->fontSize = 30;
        $captcha->length   = 4;
        $captcha->useCurve = false;
        $captcha->codeSet  = '123456789';
        return $captcha->entry();
    }


    /**
     * 发送验证码
     * @param integer $Moblie 用户昵称或手机号
     * @param return json
     */
    public function sendVerify()
    {
//        return ajaxErrorResult('已暂停注册，请稍后再试或联系管理员，谢谢');

        //验证post数据
        $postData = Request()->only('Mobile,Code,mac');
        $result = $this->validate($postData,'Login.sendVerify');
        if($result !== true){
            return ajaxErrorResult($result);
        }

        //验证验证码
        $captcha = new Captcha();
        if(!$captcha->check($postData['Code'])){
            return ajaxErrorResult('图形验证码输入错误');
        }

        //检测用户是否存在
        $isUser = db('sys_administrator')->where(['UserName|Mobile' => $postData['Mobile'],'IsDel' => 0])->find();
        if(!$isUser){
            return ajaxErrorResult('用户不存在');
        }

        //获取短信模板与用户信息组合成短信模板发送短信通知
        $smsTemp = (new SmsTemplate())->getSmsInfo('admin_login');
        $code = mt_rand(100000,999999);
        $smsTempStr = str_replace(['#name#','#code#'],[$isUser['TrueName'],$code],$smsTemp['Content']);
        //发送短信
        $result1 = (new CLApi('notice'))->sendSMS($isUser['Mobile'],$smsTempStr);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','用户登陆的验证码',$result1);

        if($result2['code'] == 0){
            //写入验证码表
            $temp = [
                'Code'       => $code,
                'Name'       => $isUser['Mobile'],
                'UpdateTime' => date('Y-m-d H:i:s',time()),
            ];
            $result3 = db('sms_code')->insert($temp);
            if($result3){
                return ajaxSuccessResult('','短信验证码发送成功');
            }
        }

        return ajaxErrorResult('短信验证码发送失败');
    }

    /*
    *发送验证码(推广页注册)
    */
    public function sendVerify_regist()
    {
//        show_error(500,'已暂停注册，请稍后再试或联系管理员，谢谢');
		
        $mobile=input('mobile');
        $code = input('code');
        //验证验证码
        $captcha = new Captcha();
        if(!$captcha->check($code)){
            show_error(500,'图形验证码输入错误');
        }

        $ret = Db::table('xb_mem_info')->where('Mobile',$mobile)->find();
        if($ret){
            $url = db('sys_basicinfo')->value('Downurl');
            $temp['url'] = $url;
            show_error(520,'该用户已经存在,请下载软件使用',$temp);
        }

        //获取短信模板与用户信息组合成短信模板发送短信通知
        $smsTemp = (new SmsTemplate())->getSmsInfo('reg_cdoe');
        $code = mt_rand(100000,999999);
        $smsTempStr = str_replace(['#name#','#code#'],['用户',$code],$smsTemp['Content']);
        $result1 = (new CLApi('notice'))->sendSMS($mobile,$smsTempStr);
        $result2 = json_decode($result1,true);

        //写入对接产品记录表
        (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','用户登陆的验证码',$result1);

        if($result2['code'] == 0){
            //写入验证码表
            $temp = [
                'Code'       => $code,
                'Name'       => $mobile,
                'UpdateTime' => date('Y-m-d H:i:s',time()),
            ];
            $result3 = db('sms_code')->insert($temp);
            if($result3){
                show_error(0,'短信验证码发送成功');
            }
        }
        show_error(500,'短信验证码发送失败，请稍后再试');
    }

    /**
     * 用户推广页注册
     * @param integer $Mobile 手机号
     * @param integer $MsgCode 短信验证码
     * @param string $puser 渠道名称
     * @return json
     */
    public function register_tuiguang()
    {
//		returnErrorResult('已暂停注册，请稍后再试或联系管理员，谢谢');
		
        //记录到访用户信息 做推广ua统计
        $this->addUserVisitRecord(2,input('puser'));

        //验证post数据
        $postData = Request()->only('Mobile,MsgCode,puser');
        $result = $this->validate($postData,'Login.register_tuiguang');
        if($result !== true){
            returnErrorResult($result);
        }

        //检测用户是否注册
        $isRes = db('mem_info')->where(['Mobile' => $postData['Mobile']])->value('ID');
        if($isRes){
            returnErrorResult('手机号已被注册，请直接登陆');
        }

        //检测推广渠道信息并对应渠道ID
        if(isset($postData['puser']) && !empty($postData['puser'])){
            $TgInfo = db('tg_admin')->where(['Name' => $postData['puser'],'IsDel' => 0])->find();
            if($TgInfo['KouliangClick'] == 0){
                returnErrorResult('此推广渠道已关闭');
            }
            if($TgInfo['Status'] == 0){
                returnErrorResult('此推广渠道已禁用');
            }
        }

        //校验短信验证码
        $msgCode = db('sms_code')->where(['Name' => $postData['Mobile']])->order('id','desc')->field(['Code','UpdateTime'])->find();
        if(!$msgCode){
            returnErrorResult('请发短信送验证码');
        }
        if((strtotime($msgCode['UpdateTime'])+300) < time()){
            returnErrorResult('短信验证码已过期，请重新发送');
        }
        if($msgCode['Code'] != $postData['MsgCode']){
            returnErrorResult('短信验证码不正确，请重新输入');
        }

        $reType = getPhoneType();
        switch ($reType){
            case 'ios':
                $reType = 2;
                break;
            case 'android':
                $reType = 1;
                break;
            default:
                $reType = 0;
        }

        //写入数据库
        $data = [
            'Mobile'    => $postData['Mobile'],
            'TgadminID' => $TgInfo['ID']??1,//推广渠道 1自来量
            'RegTime'   => date('Y-m-d H:i:s',time()),
            'LimitBalcance' => 1500,
            'Retype'    => $reType,
        ];
        $insertResult = db('mem_info')->insert($data);
        if($insertResult){
            $url = db('sys_basicinfo')->value('Downurl');
            $temp['url'] = $url;
            returnSuccessResult($temp,'注册成功，即将跳转至下载页');
        }else{
            returnErrorResult('注册失败');
        }
    }

    /**
     * 贷超角色登陆
     * @param string $UserName 用户昵称
     * @param string $Password 用户密码
     * @return Template|json
     */
    public function daichao()
    {
        if(request()->isAjax())
        {
            //验证post数据
            $postData = Request()->only('UserName,Password');
            $result = $this->validate($postData,'Login.daichao');
            if($result !== true){
                returnErrorResult($result);
            }

            //验证登陆用户信息
            $userInfo = db('sys_administrator')->where(['UserName' => $postData['UserName'],'RoleID' => 48])->find();
            if(!$userInfo){
                returnErrorResult('用户不存在');
            }
            if($userInfo['Password'] != md5($postData['Password'])){
                returnErrorResult('账户密码错误');
            }

            //更新用户登陆信息
            $temp = [
                'ID'        => $userInfo['ID'],
                'LoginTime' => date('Y-m-d H:i:s',time()),
                'LoginIP'   => request()->ip(),
            ];
            $upResult = db('sys_administrator')->update($temp);
            if(!$upResult){
                returnErrorResult('登陆失败');
            }

            //存入session 并更新用户登陆时间与IP
            session('id',$userInfo['ID']);
            session('info',$userInfo);
            (new Common())->logs('登录');

            echo json_encode(['code' => 0,'msg' => '登陆成功','data' => []],JSON_UNESCAPED_UNICODE) ;die;
        }

        //获取系统名称
        $webInfo = (new System())->getSystemInfo();
        $this->assign('title',$webInfo['SystemName']);
        $this->assign('data',$webInfo);
        return view();
    }

    /**
     * 记录到访用户信息
     * @param integer $type 到访类型 1用户访问并未注册 2用户访问并触发注册按钮
     * @param string $puser 到访用户的来源渠道 通过渠道找下到访用所属渠道
     */
    public function addUserVisitRecord($type = 1,$puser = '')
    {
        //获取访问的用户IP
        $ip = $_SERVER['REMOTE_ADDR'];

        //获取推广渠道ID
        if(isset($puser) && !empty($puser)){
            $tgAdminID = db('tg_admin')->where(['Name' => $puser])->value('ID');
        }

        //计算现在到夜晚0点的时间戳作为IP集的缓存时间
        $tomorrow = strtotime(date('Y-m-d',strtotime("+1 day")));
        $now = $tomorrow - time();

        //获取缓存的IP集，判断当前访问用户的IP是否在里面 不在就追加进去并更新缓存并将本次记录的IP追加数据库
        $ips = cache("record_ips{$type}");
        if($ips){
            if(in_array($ip,$ips)){
                \Think\Log::record('用户IP已被记录 无需再记录 '.$type);
                return;
            }else{
                array_push($ips,$ip);
                cache("record_ips{$type}",$ips,$now);
            }
        }else{
            $ips = [];
            array_push($ips,$ip);
            cache("record_ips{$type}",$ips,$now);
        }

        $temp = [
            'VisitIP' => $ip,
            'Browser' => getUserBrowser(),            //浏览器
            'System'  => getUserSystem(),             //操作系统
            'Type'    => $type,
            'TgAdminID'  => $tgAdminID??'',               //用户到访渠道ID
            'CreateTime' => date('Y-m-d H:i:s',time()),
            'PhoneType'  => getPhoneType(),           //手机类型 安卓|苹果|其它
        ];

        $result = db('tg_record')->insert($temp);
        if($result){
            \Think\Log::record('记录到访用户信息成功 '.$type);
        }else{
            \Think\Log::record('记录到访用户信息失败 '.$type);
        }
    }

    /**
     * 获取登陆方式
     * @param string $username 用户账号或手机号
     * @return json
     */
    public function getLoginType()
    {
        if(request()->isAjax())
        {
            //验证post数据
            $postData = Request()->only('Mobile');
            $result = $this->validate($postData,'Login.getLoginType');
            if($result !== true){
                ajaxErrorResult($result);
            }

            //获取用户登陆方式
            $loginType = db('sys_administrator')->where(['UserName|Mobile' => $postData['Mobile']])->value('LoginType');
            if($loginType){
                return ajaxSuccessResult($loginType,'获取登陆方式成功');
            }
            return ajaxErrorResult('用户昵称或手机号码不存在');
        }
    }

}